package com.wufun.overseas.utils;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;


import com.tencent.cos.COSClient;
import com.tencent.cos.COSClientConfig;
import com.tencent.cos.common.COSEndPoint;
import com.tencent.cos.model.COSRequest;
import com.tencent.cos.model.COSResult;
import com.tencent.cos.model.PutObjectRequest;
import com.wufun.overseas.rpc.RpcConstant;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Request;

/**
 * Cos人图片上传类
 */
public class TCUploadHelper {
    private static final String TAG = "TCUploadHelper";

    private final static int MAIN_CALL_BACK = 1;
    private final static int MAIN_PROCESS = 2;
    private final static int UPLOAD_AGAIN = 3;

    private Context mContext;
    private OnUploadListener mListerner;
    private Handler mMainHandler;

    public TCUploadHelper(final Context context, OnUploadListener listener) {
        mContext = context;
        mListerner = listener;

        mMainHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case MAIN_CALL_BACK:
                        if (mListerner != null) {
                            mListerner.onUploadResult(msg.arg1, (String) msg.obj);
                        }
                        break;
                    case UPLOAD_AGAIN:
                        Bundle taskBundle = (Bundle) msg.obj;
//                        doUploadCover(taskBundle.getString("path", ""), taskBundle.getString("netUrl", ""), taskBundle.getString("sig", ""), false);
                    default:
                        break;
                }
                return false;
            }
        });
    }

//    private String createNetUrl() {
//        return "/live_cover/" + TCUserInfoMgr.getInstance().getUserId() + "_" + System.currentTimeMillis() + ".jpg";
//    }

    private void uploadFile(final String path,String sig ,String appid, String bucket,String  directory) {
//        String appid = TCConstants.COS_APPID;
//    String appid =  "腾讯云注册的appid";
        Context context = mContext.getApplicationContext();
        String peristenceId = "";

//创建COSClientConfig对象，根据需要修改默认的配置参数
        COSClientConfig config = new COSClientConfig();
//如设置园区
        config.setEndPoint(COSEndPoint.COS_GZ);

        COSClient cos = new COSClient(context, appid, config, null);
//        String bucket = TCConstants.COS_BUCKET;
//        String cosPath = "/live_cover/" + new File(path).getName();
        final String cosPath = File.separator + directory + File.separator + new File(path).getName();
        String srcPath = path;
        String sign = sig;

        PutObjectRequest putObjectRequest = new PutObjectRequest();
        putObjectRequest.setBucket(bucket);
        putObjectRequest.setCosPath(cosPath);
        putObjectRequest.setSrcPath(srcPath);
        putObjectRequest.setSign(sign);
        putObjectRequest.setInsertOnly("0");
        putObjectRequest.setListener(new com.tencent.cos.task.listener.IUploadTaskListener() {
            @Override
            public void onProgress(COSRequest cosRequest, long l, long l1) {

            }

            @Override
            public void onCancel(COSRequest cosRequest, COSResult cosResult) {
                Message msg = new Message();
                msg.what = MAIN_CALL_BACK;
                msg.arg1 = cosResult.code;
                msg.obj = cosResult.msg;
                mMainHandler.sendMessage(msg);
            }

            @Override
            public void onSuccess(COSRequest cosRequest, COSResult cosResult) {
                Log.w(TAG, "uploadCover do upload onSuccess,");
                Message msg = new Message();
                msg.what = MAIN_CALL_BACK;
                msg.arg1 = 0;
//                msg.obj = cosResult.msg;
                msg.obj = cosPath;

                mMainHandler.sendMessage(msg);
            }

            @Override
            public void onFailed(COSRequest cosRequest, COSResult cosResult) {
                Log.w(TAG, "uploadCover do upload fail,");
                Message msg = new Message();
                msg.what = MAIN_CALL_BACK;
                msg.arg1 = cosResult.code;
                msg.obj = cosResult.msg;
                mMainHandler.sendMessage(msg);
            }
        });
        cos.putObject(putObjectRequest);
    }

    private void doUploadCover(final String path, final String sig, final String appid, final String bucket, final String  directory) {
        new Thread() {
            @Override
            public void run() {
                uploadFile(path, sig, appid,  bucket,  directory);
            }
        }.start();
    }

//    public void uploadCover(final String filePath,String uid,String token) {
//        Map<String, String> params = new HashMap<>();
////        params.put("Action", "UploadCover");
//        params.put("uid", uid + "");
//        params.put("token", token);
//        OkHttpClientManager.ResultCallback callback = new OkHttpClientManager.ResultCallback<PaMgrBean.Response<PaMgrBean.Response.UplocadCover>>() {
//            @Override
//            public void onError(Request request, Exception e) {
//                if (mListerner != null) {
//                    mListerner.onUploadResult(-1, null);
//                }
//            }
//
//            @Override
//            public void onResponse(PaMgrBean.Response<PaMgrBean.Response.UplocadCover> response) {
//                if (response != null && response.getError() == 0) {
//                    PaMgrBean.Response.UplocadCover respons = response.getData();
//                    String appid = respons.getAppId();
//                    String signature = respons.getSignature();
//                    String bucket = respons.getBucket();
//                    String directory = respons.getUploadDir();
//
//                    uploadFile(filePath, signature, appid, bucket, directory);
//                } else {
//                    onError(null, null);
//
//                }
//            }
//        };
//
//            postAsyn(RpcConstant.SVR_POST_URL +"/interface/getcossign", params, callback);
//
//    }
//    private static void postAsyn(String url, Map<String, String> params, final OkHttpClientManager.ResultCallback callback) {
//        OkHttpClientManager.postAsyn(url, params, callback);
//    }

    public interface OnUploadListener {
        void onUploadResult(int code, String url);
    }

}
